<?php

// 美化终端输出的尝试，因字符不等宽，未达到效果

class Bcho {
	public string $title = '';
	public array $lines = [];
	public int $gap = 4;

	public function __construct($title) {
		$this->title = $title;
	}

	public function addLine(string $text): static
	{
		$this->lines[] = $text;
		return $this;
	}

	public function strLen(string $text): int {
		return mb_strlen($text, 'utf-8') ?: 0;
	}

	public function gatherLineInfo(string $text): array
	{
		return [
			'len' => $this->strLen($text),
			'text' => $text,
		];
	}

	public function dump(): void {
		$maxLen = $this->strLen($this->title);
		$lineInfoList = [$this->gatherLineInfo($this->title)];
		foreach ($this->lines as $line) {
			$lineInfo = $this->gatherLineInfo($line);
			$lineInfoList[] = $lineInfo;
			if ($lineInfo['len'] > $maxLen) {
				$maxLen = $lineInfo['len'];
			}
		}
		$lineInfoList[] = ['text' => '', 'len' => 0];
		$n = count($lineInfoList);

		var_dump($lineInfoList);
		foreach ($lineInfoList as $i => &$lineInfo) {
			if ($i === 0) {
				$ll = ceil(($maxLen - $lineInfo['len']) / 2) + ($this->gap - 1);
				$rl = $maxLen - $ll - $lineInfo['len'] - 1;
				$b = '╔' . mb_str_pad('', $ll, '═');
				$b .= $lineInfo['text'];
				$b .= mb_str_pad('', $rl, '═') . '╗';
			} elseif ($i == $n - 1) {
				$l = $maxLen - 2;
				$b = '╚' . mb_str_pad('', $l, '═') . '╝';
			} else {
				$b = mb_str_pad('', $this->gap, ' ') . $lineInfo['text'];
				$b .= mb_str_pad('', ($maxLen - $lineInfo['len'] + $this->gap), ' ');
			}
			$lineInfo['b'] = $b;
			echo $b . "\n";
		}
	}
}
